<template>
  <div class="menu-outer">
    <!-- 搜索版块 -->
    <div class="search_box">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="歌手名">
          <el-input placeholder="歌手名" v-model="searchInfo" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button
            type="primary"
            @click="
              () => {
                searchInfo = '';
                set();
              }
            "
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="list_box_but1">
      <el-button
        type="primary"
        @click="
          dialogFormVisible = true;
          operate = 1;
        "
        >新增歌手</el-button
      >
      <el-button type="primary" @click="deleteAll">批量删除</el-button>
    </div>

    <div class="list_box1">
      <div class="list_table">
        <el-table
          size="small"
          :data="data"
          :height="tableHeight"
          @selection-change="handleSelectionChange"
          stripe
          :header-cell-style="{ background: '#EEF1F6' }"
        >
          <el-table-column
            type="selection"
            width="40"
            align="center"
          ></el-table-column>
          <el-table-column
            label="ID"
            prop="id"
            width="50"
            align="center"
          ></el-table-column>
          <el-table-column
            label="歌手图片"
            prop="pic"
            width="110"
            align="center"
          >
            <template v-slot="scope">
              <div class="singer-img">
                <img :src="getUrl(scope.row.singerPic)" style="width: 100%" />
              </div>
              <el-upload
                ref="uploadRef"
                class="upload"
                :action="getUrl('/mv/upload')"
                :data="{ type: 'singers' }"
                :auto-upload="true"
                :show-file-list="false"
                :on-success="(response:any) => updateInfo(response, scope.row.id)"
              >
                <el-button>更新图片</el-button>
              </el-upload>
            </template>
          </el-table-column>
          <el-table-column
            label="歌手"
            prop="name"
            width="120"
            align="center"
          ></el-table-column>
          <el-table-column label="性别" prop="sex" width="60" align="center">
            <template v-slot="scope">
              <div>{{ changeSex(scope.row.sex) }}</div>
            </template>
          </el-table-column>
          <el-table-column
            label="出生日期"
            prop="birth"
            width="120"
            align="center"
          >
            <template v-slot="scope">
              <div>{{ getBirth(scope.row.birth) }}</div>
            </template>
          </el-table-column>
          <el-table-column
            label="地区"
            prop="location"
            width="100"
            align="center"
          ></el-table-column>
          <el-table-column label="简介" prop="introduction">
            <template v-slot="scope">
              <el-scrollbar height="100px">
                <p>
                  {{ scope.row.introduction }}
                </p>
              </el-scrollbar>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160" align="center">
            <template v-slot="scope">
              <el-button @click="editRow(scope.row)">编辑</el-button>
              <el-button type="danger" @click="deleteRow(scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="list_pagination">
      <el-pagination
        class="pagination"
        background
        layout="total, prev, pager, next"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="tableData.length"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
    <!-- 内容版块 -->

    <el-dialog
      v-model="dialogFormVisible"
      :title="operate ? '添加歌手' : '修改歌手'"
      width="500"
      center
      :destroy-on-close="true"
      @close="clearInfo"
    >
      <el-form
        ref="formRef"
        :model="infoForm"
        :hide-required-asterisk="true"
        label-width="100px"
      >
        <el-form-item
          prop="name"
          label="歌手名称"
          :rules="{
            required: true,
            message: '歌手名称不能为空',
            trigger: 'blur',
          }"
        >
          <el-input v-model="infoForm.name" />
        </el-form-item>
        <el-form-item
          prop="sex"
          label="歌手性别"
          :rules="{
            required: true,
            message: '歌手性别不能为空',
            trigger: 'blur',
          }"
        >
          <el-radio-group v-model="infoForm.sex">
            <el-radio :value="1">男</el-radio>
            <el-radio :value="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          prop="birth"
          label="出生日期"
          :rules="{
            required: true,
            message: '出生日期不能为空',
            trigger: 'blur',
          }"
        >
          <el-date-picker
            v-model="infoForm.birth"
            type="date"
            placeholder="选择出生日期"
            :disabled-date="disabledDate"
          />
        </el-form-item>
        <el-form-item
          prop="location"
          label="地区"
          :rules="{
            required: true,
            message: '地区不能为空',
            trigger: 'blur',
          }"
        >
          <el-select v-model="infoForm.location" placeholder="地区">
            <el-option
              v-for="item in AREA"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="introduction"
          label="简介"
          :rules="{
            required: true,
            message: '详情不能为空',
            trigger: 'blur',
          }"
        >
          <el-input v-model="infoForm.introduction" :rows="5" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel(formRef)">取消</el-button>
          <el-button type="primary" @click="submit(formRef)"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 删除一个数据 -->
    <Deldialog
      :delVisible="delVisible"
      @confirm="confirm"
      @cancelRow="delVisible = $event"
      @closeDialog="closeDialog"
    />
    <!-- 批量删除多个数据 -->
    <Deldialog
      :delVisible="delAllVisible"
      @confirm="confirmAll"
      @cancelRow="delAllVisible = $event"
      @closeDialog="closeAllDialog"
    />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";
import {
  getAllSinger,
  delSinger,
  delSingers,
  updateSinger,
  addSinger,
} from "@/api";
import { getUrl, AREA } from "@/utils copy/format";
import type { FormInstance } from "element-plus";
const tableData = ref([]); // 记录歌曲，用于显示
const currentPage = ref(1);
const pageSize = ref(10);
const multipleSelection = ref([]); // 记录当前要删除的列表
const data = ref([]);
const tableHeight = ref(0);
const searchInfo = ref("");
tableHeight.value = window.innerHeight - 205;
const operate = ref(1);
const formRef = ref<FormInstance>();
const dialogFormVisible = ref(false);
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now();
};
const infoForm = ref({
  name: "",
  sex: -1,
  birth: "",
  location: "",
  introduction: "",
});
let operateId: number;
const handleCurrentChange = (val: any) => {
  currentPage.value = val;
  console.log(`current page: ${val}`);
  getData();
};
async function updateInfo(response: any, id: number) {
  await updateSinger({ id, singerPic: response.data });
  set();
}
async function handleSearch() {
  currentPage.value = 1;
  tableData.value = data.value = await getAllSinger(searchInfo.value.trim());
}
function getData() {
  searchInfo.value = "";
  data.value = tableData.value.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
  );
}
function handleSelectionChange(val: any) {
  multipleSelection.value = val;
}
const submit = (formEl: any) => {
  if (!formEl) return;
  formEl.validate(async (valid: any) => {
    if (valid) {
      let res: any;
      if (operate.value) {
        res = await addSinger(infoForm.value);
      } else {
        res = await updateSinger({ ...infoForm.value, id: operateId });
      }
      console.log(res);
      if (res) {
        ElMessage.success("操作成功");
      } else {
        ElMessage.error("操作失败");
      }
      set();
      dialogFormVisible.value = false;
    } else {
      console.log("error submit!");
      return false;
    }
  });
};
const cancel = (formEl: any) => {
  dialogFormVisible.value = false;
  infoForm.value = {
    name: "",
    sex: -0,
    birth: "",
    location: "",
    introduction: "",
  };
  formEl.resetFields();
};
const clearInfo = () => {
  infoForm.value = {
    name: "",
    sex: -1,
    birth: "",
    location: "",
    introduction: "",
  };
};
const editRow = (row: any) => {
  operate.value = 0;
  infoForm.value = row;
  operateId = row.id;
  dialogFormVisible.value = true;
};
function changeSex(value: any) {
  if (value === 2) {
    return "女";
  } else if (value === 1) {
    return "男";
  } else if (value === "男" || value === "女") {
    return value;
  }
}
// 解析日期
function getBirth(cellValue: any) {
  if (cellValue == null || cellValue == "") return "";
  const date = new Date(cellValue);
  const year = date.getFullYear();
  const month =
    date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1;
  const day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  return year + "-" + month + "-" + day;
}
async function set() {
  currentPage.value = 1;
  tableData.value = [];
  const singers = await getAllSinger("");
  tableData.value = singers;
  getData();
}
onMounted(() => {
  set();
});
//添加数据
import Deldialog from "@/views/components/Deldialog.vue";
const multipleSelectionId = ref({}); // 记录当前要删除的列表的用户id
const delVisible = ref(false); // 显示删除框
const delAllVisible = ref(false); // 显示批量删除框
const idx = ref(-1); // 记录当前要删除的行
function deleteRow(id: number) {
  idx.value = id;
  delVisible.value = true;
  console.log("运行过了", delVisible);
}
async function confirmAll() {
  const success = await delSingers(multipleSelectionId.value);
  if (success) {
    set();
    ElMessage.success("批量删除用户成功");
  } else {
    ElMessage.error("删除失败");
  }
  delAllVisible.value = false;
}
function closeAllDialog() {
  delAllVisible.value = false;
}
async function confirm() {
  const success = await delSinger(idx.value);
  console.log("confirm运行了");
  if (success) {
    set();
    ElMessage.success("删除成功");
  } else {
    ElMessage.error("删除失败");
  }
  delVisible.value = false;
}
function closeDialog() {
  delVisible.value = false;
}

//删除所有选中数据
function deleteAll() {
  multipleSelectionId.value = [];
  for (let item of multipleSelection.value) {
    multipleSelectionId.value.push(item.id);
  }
  delAllVisible.value = true;
  console.log("批量" + delAllVisible.value + multipleSelectionId.value);
}
//添加编辑歌手信息
</script>
<style lang="scss" scoped>
@import "@/static/css/common.scss";

svg {
  width: 14px;
  height: 14px;
  fill: #fff;
  margin-right: 4px;
}

:deep(.el-table__cell) {
  border-bottom: none !important;
}

.inner_icon {
  fill: #4d70ff;
  margin-right: 2px;
}

.inner_icon:hover {
  fill: #2d56fa;
}

.menu-outer {
  padding-bottom: 10px;
}

.list_box1 {
  text-indent: 0;
  background: #fff;
  border-radius: 4px;
  overflow: auto;
}
.list_box_but,
.list_table {
  width: 98%;
  margin: 0 auto;
  margin-top: 10px;
}
.list_box_but1 {
  position: absolute;
  top: 18px;
  right: 30px;
}
.list_box_but a {
  color: #fff;
}
.list_pagination {
  //padding-top: 14px;
  text-indent: 0;
  > div {
    justify-content: flex-end;
    margin-right: 20px;
  }
}
</style>
